package com.util.vmwareops;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

public class NetworkOps {
    public static synchronized void updateNetwork(Connection con, Map<String, NetworkInfo> networkInfoMap, String versionId) throws SQLException {

        Statement st = con.createStatement();
        for(NetworkInfo networkInfo : networkInfoMap.values()) {
            String sql_command = String.format(
                    "insert into resource_bundle_vsphere_network values(\"%s\", \"%s\", \"%s\", \"%s\", \"%s\")",
                    networkInfo.getId(),
                    networkInfo.getVc().getId(),
                    networkInfo.getNetworkName(),
                    networkInfo.getPortGroupType(),
                    networkInfo.getVersionId()
            );
            st.execute(sql_command);
        }
    }
    public static Map<String, NetworkInfo> getNetworkInfoByVersionId(String versionId) throws InterruptedException {
        DBConnectionPool db = DBConnectionPoolFactory.getDBConnectionPool("vmwareops");
        Connection con = db.getConnection();
        Map<String, NetworkInfo> networkInfos = new HashMap<String, NetworkInfo>();
        String sql = String.format("select * from %s where version=\'%s\'", "resource_bundle_vsphere_network", versionId);
        try {
            Statement stmt = con.createStatement();
            ResultSet res = stmt.executeQuery(sql);
            if(res == null) {
                return null;
            }
            while(res.next()) {
                networkInfos.put(
                        res.getString("id"),
                        new NetworkInfo(
                                res.getString("id"),
                                null,
                                res.getString("network_domain_name"),
                                res.getString("portgroup_type"),
                                res.getString("version")
                        )
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(con != null) {
                db.close(con);
            }
        }
        return networkInfos;
    }
}
